package org.monitor.controller.malog;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.monitor.config.MonitorConfig;
import org.monitor.http.DownloadClient;
import org.monitor.http.RestClient;
import org.monitor.http.RestResult;
import org.monitor.model.MonitorStateManager;
import org.monitor.servlet.controller.Controller;

/**
 * 监控停启用控制
 * @author zhaojjd
 *
 */
public class MASettingController extends Controller {
	
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");

	public void start(){
		getPairs().checkRequired("ip", "port");
		
		String ip = getPair("ip");
		String port = getPair("port");
		String monitor = getPair("monitor");
		
		String url = getRemoteUrl(ip, port);
		
		RestClient client = new RestClient(url);
		client.addPair("status", "start");
		client.addPair("monitor", MonitorStateManager.ANONYMOUS.equals(monitor) ? "" : monitor);
		RestResult rst = client.execute();
		
		if(rst.getState() == 0){
			MonitorStateManager.getServerInstance().start(ip, port, monitor);
		}else {
			if(rst.getState() != -1){
				rst.setMsg("服务器请求出错，错误码["+rst.getState()+"]，请确认：" + url);
				rst.setState(-1);
			}else {
				rst.setMsg("服务器请求出错，请确认：" + url);
			}
		}
		
		renderJson(rst);
	}
	
	public void stop(){
		getPairs().checkRequired("ip", "port");
		
		String ip = getPair("ip");
		String port = getPair("port");
		String monitor = getPair("monitor");
		
		String url = getRemoteUrl(ip, port);
		
		String filename = format.format(new Date()) + ".log";
		String dist = getStoreFile(ip, port, monitor, filename).getPath();
		
		RestResult rst = downloadMonitorFile(url, "stop", MonitorStateManager.ANONYMOUS.equals(monitor) ? "" : monitor, dist);
		if(rst.getState() != 0){
			for (int i = 0; i < 3; i++) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
				}
				rst = downloadMonitorFile(url, "obtain", MonitorStateManager.ANONYMOUS.equals(monitor) ? "" : monitor, dist);
				if(rst.getState() == 0){
					break;
				}
			}
		}
		
		if(rst.getState() == 0){
			MonitorStateManager.getServerInstance().stop(ip, port, monitor);
		}else {
			if(rst.getState() != -1){
				rst.setMsg("服务器请求出错，错误码["+rst.getState()+"]，请确认：" + url);
				rst.setState(-1);
			}else {
				rst.setMsg("服务器请求出错，请确认：" + url);
			}
		}
		
		renderJson(rst);
	}
	
	private String getRemoteUrl(String ip, String port){
		String url = "http://" + ip + ":" + port + MonitorConfig.get().getServlet();
		return url;
	}
	
	private RestResult downloadMonitorFile(String url, String status, String monitor, String dist){
		DownloadClient client = new DownloadClient(url);
		client.addPair("status", status);
		client.addPair("monitor", monitor);
		
		RestResult rst = client.execute(dist);
		return rst;
	}

	private File getStoreFile(String ip, String port, String monitor, String filename) {
		File storeFile = null;
		
		String storeDir = MonitorStateManager.getServerInstance().getMonitorDir(ip, port, monitor).toString();
		File store = new File(storeDir);
		if(!store.exists()){
			store.mkdirs();
		}
		
		String storeFilename = getStoreFilename(filename, store);
		storeFile = new File(store.getPath() + File.separator + storeFilename);
		if(storeFile.exists()){
			storeFile.delete();
		}
		
		return storeFile;
	}

	private String getStoreFilename(String filename, File store) {
		String storeFilename = null;
		if(MonitorConfig.get().override()){
			storeFilename = filename;
		}else {
			int index = filename.lastIndexOf(".");
			final String baseName = index != -1 ?filename.substring(0, index) : filename ;
			String suffix = index != -1 ? filename.substring(index + 1) : null;
			
			String[] files = store.list(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					return name.startsWith(baseName);
				}
			});
			
			storeFilename = baseName;
			if(files != null && files.length > 0){
				storeFilename = storeFilename + "_" + files.length;
			}
			if(suffix != null){
				storeFilename = storeFilename + "." + suffix;
			}
		}
		return storeFilename;
	}

}
